﻿function VisualCollaborationTool()
{
	function Preferences()
	{
		var instance = this;
		var preferenceItem = null;
		this.ColorsDictionary = null;
		this.MessageTemplate = null;
		this.UserInfoTemplate = null;
		this.DefaultUserIcon = null;
		this.DeaultHistoryMessageIcon = null;
		this.DefaultCommentMessageIcon = null;
		this.DefaultRepliesCount = null;

		function loadPreferences()
		{
			preferenceItem = getPreferencesItem("VC_CommonSettings");
			instance.ColorsDictionary = getColorsForMessageTypes();
			instance.MessageTemplatesArr = preferenceItem.getProperty("message_template").split(",");
			instance.UserInfoTemplate = preferenceItem.getProperty("user_info_template");
			instance.DefaultUserIcon = preferenceItem.getProperty("default_user_icon");
			instance.DeaultHistoryMessageIcon = preferenceItem.getProperty("history_icon");
			instance.DefaultCommentMessageIcon = preferenceItem.getProperty("comment_icon");
			instance.DefaultRepliesCount = preferenceItem.getProperty("replies_count", "3");
		}

		this.GetColorByType = function(type)
		{
			for (var obj in this.ColorsDictionary)
			{
				if (this.ColorsDictionary[obj].type == type)
				{
					var color = this.ColorsDictionary[obj].color;
					return color;
				}
			}
			return "";
		};

		function getColorsForMessageTypes()
		{
			if (preferenceItem != null)
			{
				var arr = [
					{ type: "Markup", color: preferenceItem.getProperty("regular_messge_color") },
					{ type: "MarkupHover", color: preferenceItem.getProperty("regular_messge_color_hover") },
					{ type: "Comment", color: preferenceItem.getProperty("regular_messge_color") },
					{ type: "CommentHover", color: preferenceItem.getProperty("regular_messge_color_hover") },
					{ type: "History", color: preferenceItem.getProperty("history_messge_color") },
					{ type: "HistoryHover", color: preferenceItem.getProperty("history_messge_color_hover") },
					{ type: "RegularHover", color: preferenceItem.getProperty("regular_messge_color_hover") },
					{ type: "Regular", color: preferenceItem.getProperty("regular_messge_color") }];
				return arr;
			}

		}

		function getPreferencesItem(preferenceName)
		{
			if (top.aras)
			{
				var itm = top.aras.IomInnovator.newItem();
				var aml = "<AML><Item type=\"{0}\" action=\"get\" select=\"*\" levels=\"1\"/></AML>".Format(preferenceName);
				itm.loadAML(aml);
				itm = itm.apply();
				return itm;
			}
			return null;
		}

		loadPreferences();
	}

	var self = this;

	this.Preferences = new Preferences();

	this.createSecureMessage = function()
	{
		return new SecureMessage();
	};

	this.createTextualSecureMessage = function(text)
	{
		var secureMessage = new SecureMessage();
		secureMessage.setProperty("from_identity", self.getCurrentIdentityId());
		secureMessage.setProperty("message_text", text);

		return secureMessage;
	};

	this.createMarkup = function()
	{
		return new Markup();
	};

	//Get identity id
	this.getCurrentIdentityId = function()
	{
		var userNd = top.aras.getLoggedUserItem();
		var identityNd = userNd.selectSingleNode("Relationships/Item[@type='Alias']/related_id/Item[@type='Identity']");
		if (!identityNd) return "";
		return identityNd.getAttribute("id");
	};

	//Object to work with Secure Messages
	function SecureMessage()
	{
		var self = this;
		var secureMessageItm = top.aras.newIOMItem("Secure Message");

		//Set property of Secure Message item
		this.setProperty = function(propertyName, propertyValue)
		{
			secureMessageItm.setProperty(propertyName, propertyValue);
		};

		//Get property of Secure Message item
		this.getProperty = function(propertyName, defaultPropertyValue)
		{
			if (SSVC.Utils.isNotNullOrUndefined(defaultPropertyValue))
			{
				defaultPropertyValue = "";
			}
			return secureMessageItm.getProperty(propertyName, defaultPropertyValue);
		};

		//Load Secure Message by id
		this.loadById = function(id)
		{
			secureMessageItm = top.aras.newIOMItem("Secure Message");
			secureMessageItm.setAttribute("action", "get");
			secureMessageItm.setAttribute("id", id);
			secureMessageItm = secureMessageItm.apply();

			if (secureMessageItm.isError())
			{
				top.aras.AlertError(secureMessageItm.getErrorString());
				return false;
			}
			return true;
		};

		//Save Secure Message item and create Community if it doesn't exist
		this.save = function(itemTypeId, configId, updateFeed)
		{
			if (SSVC.Utils.isNullOrUndefined(updateFeed))
			{
				updateFeed = false;
			}

			//Try to find Community item
			var communityItm = top.aras.newIOMItem("Community", "get");
			communityItm.setProperty("itemtype_id", itemTypeId);
			communityItm.setProperty("item_id", configId);
			communityItm = communityItm.apply();

			if (communityItm.isError())
			{
				//Community item wasn't found and we should create it
				communityItm = top.aras.newIOMItem("Community", "add");
				communityItm.setProperty("itemtype_id", itemTypeId);
				communityItm.setProperty("item_id", configId);
				communityItm = communityItm.apply();

				if (communityItm.isError())
				{
					top.aras.AlertError(communityItm.getErrorString());
					return false;
				}
			}

			//Save Secure Message item
			secureMessageItm.setAttribute("action", "add");
			self.setProperty("source_id", communityItm.getID());
			if (updateFeed)
			{
				var secureMessageNd = top.aras.saveItemEx(secureMessageItm.node, false);
				return (secureMessageNd != null);
			} else
			{
				var res = secureMessageItm.apply();
				return !res.isError();
			}

		};
	}

	//Object to work with markup
	function Markup()
	{
		var markupXml = "";
		var markupObjectArray = [];

		//Reset markup object
		this.reset = function()
		{
			markupObjectArray = [];
			markupXml = "";
		};

		//Add new markup to markup object
		this.add = function(markupObj)
		{
			markupObjectArray = [];
			var xml = "<" + markupObj.type + ">";
			for (var p in markupObj)
			{
				if (p == "type") continue;
				if (markupObj.hasOwnProperty(p))
				{
					xml += "<" + p + ">" + markupObj[p] + "</" + p + ">";
				}
			}
			xml += "</" + markupObj.type + ">";
			markupXml += xml;

			return true;
		};

		//Get XML from markup object
		this.getXml = function()
		{
			return markupXml;
		};

		//Set XML in markup object
		this.setXml = function(xml)
		{
			markupObjectArray = [];
			markupXml = xml;
			return true;
		};

		this.getConcatenatedTextFromMarkup = function()
		{
			if (markupObjectArray.length === 0)
			{
				convertFromXmlToMarkupObjectArray();
			}

			var res = "";
			for (var i = 0; i < markupObjectArray.length; i++)
			{
				var markupObject = markupObjectArray[i];
				if (markupObject.type == "text")
				{
					res += markupObject.text_content + " ";
				}
			}

			return res;
		};

		//Get all markup on specified page
		this.getAllMarkupOnPage = function(pageNumber)
		{
			if (markupObjectArray.length === 0)
			{
				convertFromXmlToMarkupObjectArray();
			}

			var res = [];
			for (var i = 0; i < markupObjectArray.length; i++)
			{
				var markupObject = markupObjectArray[i];
				if (SSVC.Utils.isNullOrUndefined(markupObject)) continue;
				if (markupObject.page > pageNumber) break;
				if (markupObject.page == pageNumber)
				{
					res[res.length] = markupObject;
					markupObjectArray[i] = null;
				}
			}

			return res;
		};

		//Get min page with markup
		this.getMinPage = function()
		{
			if (markupObjectArray.length === 0)
			{
				convertFromXmlToMarkupObjectArray();
			}

			if (markupObjectArray.length > 0)
			{
				return markupObjectArray[0].page;
			} else
			{
				return 1;
			}
		};

		//Fill markupObjectArray from xml
		function convertFromXmlToMarkupObjectArray()
		{
			var xmlDoc = SSVC.Wrap.Dojo.Xml.parse("<markup>" + markupXml + "</markup>");

			var j;
			var markupObject;
			//Get "box" markup objects
			var boxElements = xmlDoc.getElementsByTagName("box");
			for (var i = 0; i < boxElements.length; i++)
			{
				markupObject = {};
				var boxElement = boxElements[i];
				for (j = 0; j < boxElement.childNodes.length; j++)
				{
					markupObject[boxElement.childNodes[j].tagName] = boxElement.childNodes[j].textContent;
				}
				markupObject.type = "box";
				markupObjectArray[markupObjectArray.length] = markupObject;
			}

			//Get "arrow" markup objects
			var arrowElements = xmlDoc.getElementsByTagName("arrow");
			for (i = 0; i < arrowElements.length; i++)
			{
				markupObject = {};
				var arrowElement = arrowElements[i];
				for (j = 0; j < arrowElement.childNodes.length; j++)
				{
					markupObject[arrowElement.childNodes[j].tagName] = arrowElement.childNodes[j].textContent;
				}
				markupObject.type = "arrow";
				markupObjectArray[markupObjectArray.length] = markupObject;
			}

			//Get "text" markup objects
			var textElements = xmlDoc.getElementsByTagName("text");
			for (i = 0; i < textElements.length; i++)
			{
				markupObject = {};
				var textElement = textElements[i];
				for (j = 0; j < textElement.childNodes.length; j++)
				{
					markupObject[textElement.childNodes[j].tagName] = textElement.childNodes[j].textContent;
				}
				markupObject.type = "text";
				markupObjectArray[markupObjectArray.length] = markupObject;
			}

			markupObjectArray.sort(function(a, b)
			{
				if (a.page == b.page)
				{
					if (a.type == b.type) return 0;
					if (a.type > b.type)
					{
						return 1;
					} else
					{
						return -1;
					}
				} else
				{
					return a.page - b.page;
				}
			});

			return true;
		}
	}

	//Get file url by vault id
	this.getFileUrlByFileId = function(vaultUrl)
	{
		try
		{
			var fileId = vaultUrl.replace(/vault:\/\/\/\?fileid\=/i, "");
			return top.aras.IomInnovator.getFileUrl(fileId, top.Enums.UrlType.SecurityToken);
		}
		catch (e)
		{
			return "";
		}
	};
}

SSVC.Wrap.Dojo.SetObject("SSVC.VisualCollaborationTool", new VisualCollaborationTool());